#pragma once
#include<iostream>
#include<cstring>
#include<cerrno>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"nocopy.hpp"
#include"Comm.hpp"
#include"Log.hpp"
#include"InetAddr.hpp"
#include<unistd.h>
#include<sys/wait.h>
const static uint16_t defaultport=8888;
const static int defaultsize = 1024;
const static int default_backlog=5;

using namespace LogModule;

class TcpServer:public nocopy
{
    public:
    TcpServer(uint16_t port=defaultport):_port(port),_isrunning(false)
    {
    }
    void Init()
    {
        //创建socket
        _listensocket=socket(AF_INET,SOCK_STREAM,0);//监听socket
        if(_listensocket<0)
        {
            LOG(LogModule::LogLevel::ERROR)<<"socket error,"<<errno<<":"<<strerror(errno);
            exit(Socket_Err);
        }
        int opt=1;
        setsockopt(_listensocket, SOL_SOCKET, SO_REUSEADDR |SO_REUSEPORT, &opt, sizeof(opt));
        LOG(LogModule::LogLevel::INFO)<<"socket success,socketfd:"<<_listensocket;
        //绑定
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);//一定要本地转网络
        local.sin_addr.s_addr=INADDR_ANY;//任意一个ip都可以
        //local.sin_addr.s_addr=inet_addr(_ip.c_str());//设置为指定ip
        int n=::bind(_listensocket,CONV(&local),sizeof(local));
        if(n!=0)
        {
            LOG(LogModule::LogLevel::ERROR)<<"bind error,"<<errno<<":"<<strerror(errno);
            exit(Bind_Err);
        }
        //设置为监听状态
        if(listen(_listensocket,default_backlog))
        {
            LOG(LogModule::LogLevel::ERROR)<<"listen error,"<<errno<<":"<<strerror(errno);
            exit(Listen_Err);
        }
        LOG(LogModule::LogLevel::INFO)<<"监听套接字成功"<<_listensocket;
    }
    static void* Service(void* sock)//全双工，有读，写两个缓冲区
    {
        int sockfd=*(int*)sock;
        delete (int*)sock;
        char buffer[1024];
        while(true)
        {
            ssize_t n=read(sockfd,buffer,sizeof(buffer));
            if(n>0)//正常获取
            {
                buffer[n]=0;
                std::cout<<buffer<<std::endl;
                std::string echo="server echo#";
                echo+=buffer;
                write(sockfd,echo.c_str(),echo.size());
            }
            else if(n==0)
            {
                //客户端断开连接
                LOG(LogModule::LogLevel::INFO)<<"客户端断开连接:"<<sockfd;
                break;
            }
            else
            {
                LOG(LogModule::LogLevel::ERROR)<<"read socket error,"<<errno<<":"<<strerror(errno);
                break;
            }
        }
        close(sockfd);
        LOG(LogModule::LogLevel::INFO)<<"关闭套接字:"<<sockfd;
        return nullptr;
    }
    void ProcessService(int sockfd)
    {
        pthread_t tid;
        int* fd=new int(sockfd);
        int n=pthread_create(&tid,nullptr,Service,fd);
        pthread_detach(tid);
    }
    void start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sockfd=accept(_listensocket,CONV(&peer),&len);//获取与客户端的通信套接字
            if(sockfd<0)
            {
                LOG(LogModule::LogLevel::ERROR)<<"accept error,"<<errno<<":"<<strerror(errno);
                continue;
            }
            LOG(LogModule::LogLevel::INFO)<<"建立连接成功:"<<sockfd;
            ProcessService(sockfd);
        }
    }
    ~TcpServer(){}
    private:
    uint16_t _port;
    int _listensocket;
    bool _isrunning;
};